
const baseURL = 'https://szsensing.com:8581'
/* const baseURL = 'http://203.195.170.235:8581' */

const httpInterceptor = {
  // 请求前拦截器
  invoke: (options: UniApp.RequestOptions) => {
    if (!options.url.startsWith('https')) {
      options.url = baseURL + options.url
    }
    options.timeout = 10000
  },
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

type Data<T> = {
  code: string
  msg: string
  data: T
}
//小程序没有响应拦截器，自己手动封装
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      //响应成功
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          uni.navigateTo({
            url: '/pages/login/login',
          })
          reject(res)
        } else {
          uni.showToast({
            title: (res.data as Data<T>).msg || '请求失败',
            icon: 'none',
          })
          reject(res)
        }
      },
      fail(err) {
        uni.showToast({
          title: '网络错误',
          icon: 'none',
        })
        reject(err)
      },
    })
  })
}



